package 美团;

import java.util.*;

/**
 * @Author Weton Li
 * @Date 2021/3/13 17:24
 */
public class Test3 {

    public int method1(int[] nums) {
        if (nums.length == 1){
            return nums[0];
        }
        HashMap<Integer, Integer> map = new HashMap<>();
        int result = 0;
        for (int i = 0; i < nums.length; i++) {
            if (!map.containsKey(nums[i])) {
                map.put(nums[i],1);
            }else {
                if (map.get(nums[i])>nums.length/2){
                    result = nums[i];
                    break; // 退出循环！
                }else {
                    map.put(nums[i],map.get(nums[i]+1));
                }
            }
        }
        return result;
    }
    // 排序，统计出现重复数最多数的次数
    public int method2(int[] nums){
        if (nums.length == 1) {
            return nums[0];
        }
        int sum =1;
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 1; i++) {
            if (nums[i] == nums[i+1]){
                sum++;
                if (sum > nums.length / 2) {
                    return nums[i];
                }
            }else {
                sum = 1;
            }
        }
        return 0;
    }


    public static void main(String[] args) {
        Test3 test3 = new Test3();
        int[] input = {1,2,4,4,4,5};
        int method1 = test3.method1(input);
        System.out.println(method1);
        int method2 = test3.method2(input);
        System.out.println(method2);
    }
}
